﻿using SceneEngine;
using System.Windows.Forms;
using System;

namespace SceneEditor
{
    public class AddObjectGroupAction : EditAction
    {
        private string groupPath;
        private TreeView objectTree;

        public AddObjectGroupAction(string groupPath, TreeView objectTree)
        {
            this.groupPath = groupPath;
            this.objectTree = objectTree;
        }

        public override void Undo()
        {
            string[] pathSplit = groupPath.Split('|');
            TreeNodeCollection treeNodes = objectTree.Nodes;

            for (int i = 0; i < pathSplit.Length - 1; i++)
            {
                treeNodes = treeNodes[pathSplit[i]].Nodes;
            }

            TreeNode node = treeNodes[pathSplit[pathSplit.Length - 1]];

            if (node.Nodes.Count > 0)
            {
                throw new Exception("Tried to remove an object group while it still has nodes. " +
                                    "The undo chain must have messed up.");
            }

            node.Remove();
        }

        public override void Redo()
        {
            string[] pathSplit = groupPath.Split('|');
            TreeNodeCollection treeNodes = objectTree.Nodes;

            for (int i = 0; i < pathSplit.Length - 1; i++)
            {
                treeNodes = treeNodes[pathSplit[i]].Nodes;
            }

            if (treeNodes.ContainsKey(pathSplit[pathSplit.Length - 1]) == false)
            {
                treeNodes.Insert(0,
                                 pathSplit[pathSplit.Length - 1],
                                 pathSplit[pathSplit.Length - 1],
                                 0);
            }
        }
    }
}
